package skurro.firstsql;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.TrafficStats;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.internal.os.PowerProfile;

public class MainActivity extends Activity {
	
	// for cell identification
	private final static String  API_KEY = "INSERT KEY HERE";
	 
	private TelephonyManager tm;
	private GsmCellLocation location;
	private int cid, lac, mcc, mnc, cellPadding;	

	// TODO define better
	// for other stuff
	public static final String TAG = "FindFriends";
	// Intent request codes
    private static final int REQUEST_ENABLE_BT = 2;
	public final static String KEY = "friendArray";
	
	public static final boolean D = true;
	
	WifiManager wifi;       
    ListView lv;
    //TextView textStatus;
    Button btnScan;    
    Button btnCheckForFriends;
    
    
   
    
    int size = 0;
    int currBtSize = 0;
    int currWifiSize = 0;
    int uIDint =0;
    
    long bytesStart = 0;

    long totalBytesNow = 0;
    long bytesDiff = 0;

    
    String ITEM_KEY = "key";
    String phoneName="";
    String uID ="";
    String btMacAddr ="";
    String wifiMacAddr = "";
    
    List<ScanResult> results;
    ArrayList<String> wifiArraylist = new ArrayList<String>();
    ArrayList<String> btArrayList = new ArrayList<String>();
    
    PowerProfile mPowerProfile;
    BluetoothAdapter btAdapter; 
    SimpleAdapter adapter;
    BroadcastReceiver receiver;
    String[] myFriendsArray;
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         
         if(D) Log.e(TAG, "+++ ON CREATE +++");
         btAdapter= BluetoothAdapter.getDefaultAdapter();
         wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
         WifiInfo wifiInf = wifi.getConnectionInfo();
         
         // If BT is not on, request that it be enabled.
         // setupChat() will then be called during onActivityResult
         if (!btAdapter.isEnabled()) 
         {
             Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BT);
         }
         if(!wifi.isWifiEnabled())
         {
         	wifi.setWifiEnabled(true);
         	
         }
         phoneName = btAdapter.getName();
         uID = Secure.getString(this.getContentResolver(),Secure.ANDROID_ID);
         btMacAddr = btAdapter.getAddress();
         wifiMacAddr = wifiInf.getMacAddress();
         
         // for cell tower identification
         tm = (TelephonyManager) getSystemService(Context .TELEPHONY_SERVICE);
         
         // Register for broadcasts when a device is discovered
         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
         this.registerReceiver(mReceiver, filter);

         // Register for broadcasts when discovery has finished
         filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
         this.registerReceiver(mReceiver, filter);


    	try 
    	{
    		btnScan = (Button) findViewById(R.id.buttonScan);
    		btnScan.setOnClickListener((new View .OnClickListener() {
			   public void onClick(View  v) { if(D) Log.e(TAG, "+++ ON Scan +++");
				   try{
					   
					   phoneName = btAdapter.getName();
				         btMacAddr = btAdapter.getAddress();
				         //wifiMacAddr = wifiInf.getMacAddress();
				         ;
			        	 
				         ((TextView) findViewById(R.id.TextPhoneName)).setText("Phone Name: "
					    	      + phoneName);
				         ((TextView) findViewById(R.id.TextBTID)).setText("Bluetooth ID: "
					    	      + btMacAddr);
				     
				   //TODO Clear bt and Wifi list before every scan. 
				   // for cell tower id
				    location = (GsmCellLocation) tm.getCellLocation();
		    	    cid = location.getCid();
		    	    lac = location.getLac();
		    	    if(D) Log.e(TAG, "+++ got info +++");
		    	    /*
		    	     * Mcc and mnc is concatenated in the networkOperatorString. The first 3
		    	     * chars is the mcc and the last 2 is the mnc.
		    	     */
		    	    String  networkOperator = tm.getNetworkOperator();
		    	    if(D) Log.e(TAG, "+++ got operator +++");
		    	    if (networkOperator != null && networkOperator.length() > 0) {
		    	     try {
		    	      mcc = Integer .parseInt(networkOperator.substring(0, 3));
		    	      mnc = Integer .parseInt(networkOperator.substring(3));
		    	     } catch (NumberFormatException  e) {
		    	     }
		    	    }
		    	 
		    	    /*
		    	     * Check if the current cell is a UMTS (3G) cell. If a 3G cell the cell id
		    	     * padding will be 8 numbers, if not 4 numbers.
		    	     */
		    	    if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS) {
		    	     cellPadding = 8;
		    	    } else {
		    	     cellPadding = 4;
		    	    }
		    	    if(D) Log.e(TAG, "+++ lets make it pretty +++");
		    	    		((TextView) findViewById(R.id.TextCellID)).setText("CellID: "
		    	    	      + getPaddedHex(cid, cellPadding));
		    	    	    ((TextView) findViewById(R.id.TextLac)).setText("Lac: "
		    	    	      + getPaddedHex(lac, 4));
		    	    	    ((TextView) findViewById(R.id.TextMcc)).setText("Mcc: "
		    	    	      + getPaddedInt(mcc, 3));
		    	    	    ((TextView) findViewById(R.id.TextMnc)).setText("Mnc: "
		    	    	      + getPaddedInt(mnc, 2));
			    	
		    	    // for bluetooth and wifi
			        btArrayList.clear();
			        doDiscovery();
			        
			       // Toast.makeText(this, "Scanning Bluetooth....", Toast.LENGTH_SHORT).show();
			        
			        
			        wifiArraylist.clear();  
			        Log.i("arraylist size", String.valueOf(wifiArraylist.size()));
			        wifi.startScan();
			        
			        //Log.v("first test", "You think you look like god");
			        results = wifi.getScanResults();
			    	//Log.v("second test", "What is wrong with you?");
			        size = results.size();
			       // Log.v("third test", "Break hearts just to feed the anger");
			        currBtSize = btArrayList.size();
			        
			       
			        //Toast.makeText(this, "Scanning Wifi...." + size, Toast.LENGTH_SHORT).show();
			        try 
			        {
			        	currWifiSize = size;
			            size = size - 1;
			            while (size >= 0) 
			            {   
			                                       
			                wifiArraylist.add(results.get(size).BSSID);
			                size--;
			                               
			            }
			           
			        }
			        catch(Exception e)
			        {
			        	Log.i("onClick Scan", e.toString());
			            e.printStackTrace();
			        }
			        
			        finally
			        {
			        	
			        }
			   	}
				   catch(Exception e)
				   {
					   Log.i("onClick Scan", e.toString());
			            e.printStackTrace();
				   }
				   finally
				   {
					   //make scan pretty
				        ((TextView) findViewById(R.id.TextBTNum)).setText("number of Bluetooth devices: " 
			            		+ "Scanning...");
			          ((TextView) findViewById(R.id.TextWIFINum)).setText("number of WIFI access points: "
			  	    	      + currWifiSize);
				   }
			   }
			  
			}
			));
		   
		

			btnCheckForFriends = (Button) findViewById(R.id.buttonFriends);
			btnCheckForFriends.setOnClickListener((new View.OnClickListener() {
			   public void onClick(View  v) {
				   
				   //TODO if bluetooth device is a phone, then make friends with it too.
				  try
		    		{
					bytesStart = TrafficStats.getTotalTxBytes() + TrafficStats.getTotalRxBytes();
					
					double batLvl = getBatteryLife();
		        	 String bat = String.valueOf(batLvl);
		                	 

		        	 ((TextView)findViewById(R.id.bat_info)).setText("Bat level" + bat);
					Log.i("Scanning", "you pushed the button");
		            String path = "http://people.cs.uct.ac.za/~bdavies/Test.php";
					//String path = "http://people.cs.uct.ac.za/~bdavies/TestEvaluate.php";
		            //String path = "http://192.168.1.25/Test.php";
		            JSONObject jsonO = new JSONObject();
		            
		            JSONArray jsonBluetoothA = new JSONArray();
		            JSONArray jsonWifiA = new JSONArray();
		            try 
		            {	
		            	jsonO.put("wifiSize", currWifiSize);
		            	jsonO.put("btSize", currBtSize);
		            	jsonO.put("cell", cid);
		            	jsonO.put("name", phoneName);
		            	jsonO.put("uID", uID);
		            	jsonO.put("btID", btMacAddr);
		            	jsonO.put("wifiID", wifiMacAddr);
		            	jsonO.put("data", bytesDiff);
		                
		                
		                for(int i=0; i<currBtSize; i++)
		     			{
		                	jsonBluetoothA.put(btArrayList.get(i).toString());
		     				jsonO.put("bluetooth",jsonBluetoothA);
		     			}
		 	            
		                
			            for(int i=0; i<currWifiSize; i++)
		     			{
			            	jsonWifiA.put(wifiArraylist.get(i).toString());
		     				jsonO.put("wifi",jsonWifiA);
		     			}
		            HttpClient client = new DefaultHttpClient();
		            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
		            HttpResponse response;
		            
		           
		            Log.i("btnCheckForFriends", "btArrayList size is : " + currBtSize);
		            
		          
		          
			            
			            HttpPost post = new HttpPost(path);
		                post.setHeader("json", jsonO.toString());
		                StringEntity se = new StringEntity(jsonO.toString());
		                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
		                        "application/json"));
		                post.setEntity(se);
		                bytesStart = TrafficStats.getTotalTxBytes() + TrafficStats.getTotalRxBytes();
		                response = client.execute(post);
		                totalBytesNow = TrafficStats.getTotalTxBytes() + TrafficStats.getTotalRxBytes();
			        	bytesDiff = totalBytesNow - bytesStart;
		                
			                FileWriter file = new FileWriter("/sdcard/myJSON.txt");
			                file.write(jsonO.toString());
			                Log.i("JSONFile",jsonO.toString());
			                file.flush();
			                file.close();
		                /* Checking response */
		                if (response != null)
		                {
		                	Log.i("we got response, yo", "See?");
		                    InputStream in = response.getEntity().getContent(); // Get the data in the entity
		                    String a = convertStreamToString(in);
		                    
		                    //Log.i("Read from Server", String.valueOf(in));
		                    Log.i("Read from Server", a);
		                    
		                 
		                    
			                    JSONObject jsonIn = new JSONObject(a);
			                    JSONArray jsonInArr = jsonIn.getJSONArray("friends");
			                    int numFriends = jsonInArr.length();
			                    myFriendsArray = new String[numFriends];
			                    for(int i =0; i < numFriends; i++)
			                    {
			                    	JSONObject jsonFriend = jsonInArr.getJSONObject(i);
			                    	 
			                    	String s = jsonFriend.getString("name") + " " + jsonFriend.getString("value") + "\n";
			                         myFriendsArray[i] = s;
			                    }
			                   
			                    
			                
		                }
			                
		            } 
		            catch (Exception e) 
		        	{
		            	Log.i("onClick friendsInner", e.toString());
		                e.printStackTrace();
		        	}
		            	
		     			
		 		}
		        catch (Exception e) 
		    	{
		        	Log.i("onClick friendsOuter", e.toString());
		    	}
		     
		        finally
		        {
		        	
		        	hasFriends(myFriendsArray);
		        	totalBytesNow = TrafficStats.getTotalTxBytes() + TrafficStats.getTotalRxBytes();
		        	bytesDiff = totalBytesNow - bytesStart;

		        	 TextView infoView = (TextView)findViewById(R.id.traffic_info);
		        	 String info = "";

		        	 info += "Data Transfer:\n";
		        	 info += bytesDiff + "Bytes. \n";
		        	 

		        	 infoView.setText(info);
		        	 
		        	 TextView batView = (TextView)findViewById(R.id.bat_info);
		        	 double batLvl = getBatteryLife();
		        	 String bat = String.valueOf(batLvl);
		                	 

		        	 batView.setText(bat);
		        	 //double multiplier = mPowerProfile.getAveragePower(PowerProfile.POWER_BLUETOOTH_ACTIVE);
				       // Log.i("BluetoothPowerProfile!!", String.valueOf(multiplier));

		        }
			 }
			}));
			   
			
			
	       //lv = (ListView)findViewById(R.id.list);
	
	       
	        if (wifi.isWifiEnabled() == false)
	        {
	            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
	            wifi.setWifiEnabled(true);
	        }   
	       
	        registerReceiver(new BroadcastReceiver()
	        {
	            @Override
	            public void onReceive(Context c, Intent intent) 
	            {
	            	
	            	results = wifi.getScanResults();
	            	//size = results.size();
	               
	            }
	        }, 
	        new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    	}
    	catch (Exception e) {		
			Log.i("On Create", e.toString());
			e.printStackTrace();
		}
        finally
        {
        	
        }          
    }        
    
    public void onStart() 
    {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");
   
        
        
        
        ((TextView) findViewById(R.id.TextPhoneName)).setText("Phone Name: "
	    	      + phoneName);
        ((TextView) findViewById(R.id.TextPhoneID)).setText("Phone ID: "
	    	      + uID);
        ((TextView) findViewById(R.id.TextBTID)).setText("Bluetooth ID: "
	    	      + btMacAddr);
        ((TextView) findViewById(R.id.TextWIFIID)).setText("WIFI ID: "
	    	      + wifiMacAddr);
    }
    
//    @Override
//    public void onClick(View view) 
//    {
//
//
//    	if(view == btnScan )
//    	{
//    		// for cell tower id
//    		location = (GsmCellLocation) tm.getCellLocation();
//    	    cid = location.getCid();
//    	    lac = location.getLac();
//    	 
//    	    /*
//    	     * Mcc and mnc is concatenated in the networkOperatorString. The first 3
//    	     * chars is the mcc and the last 2 is the mnc.
//    	     */
//    	    String  networkOperator = tm.getNetworkOperator();
//    	    if (networkOperator != null && networkOperator.length() > 0) {
//    	     try {
//    	      mcc = Integer .parseInt(networkOperator.substring(0, 3));
//    	      mnc = Integer .parseInt(networkOperator.substring(3));
//    	     } catch (NumberFormatException  e) {
//    	     }
//    	    }
//    	 
//    	    /*
//    	     * Check if the current cell is a UMTS (3G) cell. If a 3G cell the cell id
//    	     * padding will be 8 numbers, if not 4 numbers.
//    	     */
//    	    if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS) {
//    	     cellPadding = 8;
//    	    } else {
//    	     cellPadding = 4;
//    	    }
//    	    		((TextView) findViewById(R.layout.activity_main)).setText("CellID: "
//    	    	      + getPaddedHex(cid, cellPadding));
//    	    	    ((TextView) findViewById(R.layout.activity_main)).setText("Lac: "
//    	    	      + getPaddedHex(lac, 4));
//    	    	    ((TextView) findViewById(R.layout.activity_main)).setText("Mcc: "
//    	    	      + getPaddedInt(mcc, 3));
//    	    	    ((TextView) findViewById(R.layout.activity_main)).setText("Mnc: "
//    	    	      + getPaddedInt(mnc, 2));
//	    	
//    	    // for bluetooth and wifi
//	        btArrayList.clear();
//	        doDiscovery();
//	        Toast.makeText(this, "Scanning Bluetooth....", Toast.LENGTH_SHORT).show();
//	        
//	        
//	        wifiArraylist.clear();          
//	        wifi.startScan();
//	        
//	        //Log.v("first test", "You think you look like god");
//	        results = wifi.getScanResults();
//	    	//Log.v("second test", "What is wrong with you?");
//	        size = results.size();
//	       // Log.v("third test", "Break hearts just to feed the anger");
//	        
//	
//	        
//	        Toast.makeText(this, "Scanning Wifi...." + size, Toast.LENGTH_SHORT).show();
//	        try 
//	        {
//	        	currWifiSize = size;
//	            size = size - 1;
//	            while (size >= 0) 
//	            {   
//	                                       
//	                wifiArraylist.add(results.get(size).BSSID);
//	                size--;
//	                               
//	            }
//	        }
//	        catch(Exception e)
//	        {
//	        	Log.i("onClick Scan", e.toString());
//	            e.printStackTrace();
//	        }
//	        
//	        finally
//	        {
//	        	
//	        }
//    	}
//    	
//    	if(view == btnCheckForFriends)
//    	{
//    		try
//    		{
//            String path = "http://people.cs.uct.ac.za/~bdavies/Test.php";
//            
//            HttpClient client = new DefaultHttpClient();
//            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
//            HttpResponse response;
//            
//            currBtSize = btArrayList.size();
//            Log.i("btnCheckForFriends", "btArrayList size is : " + currBtSize);
//            JSONObject jsonO = new JSONObject();
//            
//            JSONArray jsonBluetoothA = new JSONArray();
//            JSONArray jsonWifiA = new JSONArray();
//            try 
//            {
//            	jsonO.put("name", phoneName);
//            	jsonO.put("uID", uID);
//            	jsonO.put("btID", btMacAddr);
//            	jsonO.put("wifiID", wifiMacAddr);
//                
//                
//                for(int i=0; i<currBtSize; i++)
//     			{
//                	jsonBluetoothA.put(btArrayList.get(i).toString());
//     				jsonO.put("bluetooth",jsonBluetoothA);
//     			}
// 	            
//                
//	            for(int i=0; i<currWifiSize; i++)
//     			{
//	            	jsonWifiA.put(wifiArraylist.get(i).toString());
//     				jsonO.put("wifi",jsonWifiA);
//     			}
//	            
//	            HttpPost post = new HttpPost(path);
//                post.setHeader("json", jsonO.toString());
//                StringEntity se = new StringEntity(jsonO.toString());
//                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
//                        "application/json"));
//                post.setEntity(se);
//                response = client.execute(post);
//                
//	                FileWriter file = new FileWriter("/sdcard/myJSON.json");
//	                file.write(jsonO.toString());
//	                Log.i("JSONFile",jsonO.toString());
//	                file.flush();
//	                file.close();
//                /* Checking response */
//                if (response != null)
//                {
//                	Log.i("we got response, yo", "See?");
//                    InputStream in = response.getEntity().getContent(); // Get the data in the entity
//                    String a = convertStreamToString(in);
//                    
//                    Log.i("Read from Server", a);
//                    if(a.equals("{\"devices\":null}"))
//                    {
//                    	myFriendsArray = new String[1];
//                    	myFriendsArray[0] = "Your phone has no friends here"; 
//                   	
//                    }
//                    else
//                    {
//	                    JSONObject jsonIn = new JSONObject(a);
//	                    JSONArray jsonInArr = jsonIn.getJSONArray("devices");
//	                    int numFriends = jsonInArr.length();
//	                    myFriendsArray = new String[numFriends];
//	                    for(int i =0; i < numFriends; i++)
//	                    {
//	                    	 String s = jsonInArr.getString(i);
//	                         myFriendsArray[i] = s;
//	                    }
//	                   
//	                    
//	                }
//                }
//	                
//            } 
//            catch (Exception e) 
//        	{
//            	Log.i("onClick friendsInner", e.toString());
//                e.printStackTrace();
//        	}
//            	
//     			
// 		}
//        catch (Exception e) 
//    	{
//        	Log.i("onClick friendsOuter", e.toString());
//    	}
//     
//        finally
//        {
//        	hasFriends(myFriendsArray);
//        }
//	}
//}
    
    private void doDiscovery() {
        if (D) Log.d(TAG, "doDiscovery()");

        // Indicate scanning in the title
        setProgressBarIndeterminateVisibility(true);


        // If we're already discovering, stop it
        if (btAdapter.isDiscovering()) {
        	btAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        btAdapter.startDiscovery();
    }
    
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() 
    {
        @Override
        public void onReceive(Context context, Intent intent) 
        {
            String action = intent.getAction();
            
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) 
            {
            	Log.i("OnRecieve", "found a thing : ");
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.i("OnRecieve", "it is : " + device.getName());
                Log.i("OnRecieve", "adding to array, yeah?");
            	btArrayList.add(device.getAddress());
            	currBtSize = btArrayList.size();
            	((TextView) findViewById(R.id.TextBTNum)).setText("number of Bluetooth devices: " 
	            		+ currBtSize);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) 
                {
                	
                	
                }
                
                else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) 
                {
                    Log.i("OnRecieve", "Is that it?");
                    if (btArrayList.size() == 0) 
                    {
                        String noDevices = "Nothing :(";
                        btArrayList.add(noDevices);
                    }
                }
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            { 
            	Log.i("BTScan", "Scan Done");
            	if(currBtSize==0)
            	((TextView) findViewById(R.id.TextBTNum)).setText("number of Bluetooth devices: " 
            		+ "0");
            }
        }
    };
    
    private void hasFriends(String[] a)
    {
    	try
    	{
	    	int size = a.length;
	    	
	    	 // for friends Linear Layout
	        View ll = findViewById(R.id.listLayout);
	      ((LinearLayout) ll).removeAllViews();
		    
	    	    
	    	for(int i =0; i<size; i++)
	    	{
	    		Log.i("printing...", "hi");
	    		TextView tx = new TextView(this);
		        tx.setText(a[i]);
		        tx.setId(i);
		        tx.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		        ((LinearLayout) ll).addView(tx);
		   	}
    	}
    	catch(Exception e)
    	{
    		Log.i("hasFriends", e.toString());
    		e.printStackTrace();
    		
    	}
    	finally
    	{
    		
    	}
//    	Intent intent = new Intent(this, DisplayFriendActivity.class);
//    	Bundle b=new Bundle();
//    	b.putStringArray(KEY, a);
//    	intent.putExtras(b);
//    	startActivity(intent);
    }
    
    private static String convertStreamToString(InputStream is) 
    {
    	Log.i("converting to string", "nice");
	    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    StringBuilder sb = new StringBuilder();

	    String line = null;
	    try 
	    {
	        while ((line = reader.readLine()) != null) 
	        {
	            sb.append(line + "\n");
	        }
	    }
	    catch (IOException e) 
	    {
	        e.printStackTrace();
	    } 
	    finally 
	    {
	        try 
	        {
	            is.close();
	        } 
	        catch (IOException e) 
	        {
	            e.printStackTrace();
	        }
	    }
	    return sb.toString();
	}
    
    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    /**
     * Convert an int to an hex String and pad with 0's up to minLen.
     */
    String  getPaddedHex(int nr, int minLen) {
     String  str = Integer.toString(nr);
     if (str != null) {
      while (str.length() < minLen) {
       str = "0" + str;
      }
     }
     return str;
    }
    
    /**
     * Convert an int to String and pad with 0's up to minLen.
     */
    String  getPaddedInt(int nr, int minLen) {
     String  str = Integer .toString(nr);
     if (str != null) {
      while (str.length() < minLen) {
       str = "0" + str;
      }
     }
     return str;
    }
    public double getBatteryLife()
    {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = this.registerReceiver(null, ifilter);
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
    double bat = level/ (float)scale;
    Log.d("TRANSFER", "Battery level:"+bat);
    return bat;

    }
}
